import json
import logging

from django.http import HttpRequest
from django.views import View

from apps.user.models import User, Config
from apps.user.utils import param_register_user, param_add_user, add_user, change_password
from utils.Result import Result
from utils.UnSureJsonResponse import UnSureJsonResponse
from utils.hash import get_md5_encryption

logger = logging.getLogger('log')


class ConfigView(View):

    @staticmethod
    def get(request: HttpRequest):
        """
        获取所有配置
        """
        username = request.COOKIES.get('username').encode('latin-1').decode('utf-8')
        try:
            user = User.objects.get(username=username)
            if user.role == 1:
                # 管理员，查询配置
                config_data = Config.objects.all()
                return UnSureJsonResponse(Result.success(data=config_data, delete=['id', 'is_removed']), safe=False)
            else:
                return UnSureJsonResponse(Result.fail(code=1002, message='无权限'))
        except User.DoesNotExist:
            logger.error(f'不存在{username}')
            return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))
        except User.MultipleObjectsReturned:
            logger.error(f'存在多个用户{username}')
            return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))

    @staticmethod
    def put(request: HttpRequest):
        """
        修改配置
        body传参法:
            {config_key}: {config_value}
        """
        username = request.COOKIES.get('username').encode('latin-1').decode('utf-8')
        try:
            user = User.objects.get(username=username)
            if user.role == 1:
                # 管理员，查询配置
                param: dict = json.loads(request.body)
                for key, value in param.items():
                    Config.objects.filter(config_key=key).update(config_value=value)
                config_data = Config.objects.all()
                return UnSureJsonResponse(Result.success(data=config_data, delete=['id', 'is_removed']), safe=False)
            else:
                return UnSureJsonResponse(Result.fail(code=1002, message='无权限'))
        except User.DoesNotExist:
            logger.error(f'不存在{username}')
            return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))
        except User.MultipleObjectsReturned:
            logger.error(f'存在多个用户{username}')
            return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))


class UserView(View):

    @staticmethod
    def get(request: HttpRequest):
        """
        获取用户
        头参法:
            user_id: 用户ID，integer类型
            username: 用户名
            两个参数任选其一，不能没有
        """
        try:
            try:
                user_id = int(request.GET.get('user_id'))
                user = User.objects.get(id=user_id)
                user.role_int2role_message()
                return UnSureJsonResponse(Result.success(data=user, delete=['is_removed', 'password']))
            except (ValueError, TypeError):
                username = request.GET.get('username')
                if username is None:
                    return UnSureJsonResponse(Result.fail(code=1001, message='缺少必要参数'))
                else:
                    user = User.objects.get(username=username)
                    user.role_int2role_message()
                    return UnSureJsonResponse(Result.success(data=user, delete=['is_removed', 'password']))
        except User.DoesNotExist:
            return UnSureJsonResponse(Result.fail(code=2003, message='用户不存在'))

    @staticmethod
    def post(request: HttpRequest):
        """
        新增用户，注册用户
        密码前端需md5加密
        注册用户：
            username: 用户名
            nickname: 昵称
            password: 密码
            repeat_password: 重复密码，验证
        管理员新增用户：
            cookie:
                username: 验证信息
            username: 用户名
            nickname: 昵称
            password: 可选项，不选则为默认密码
            role: 可选超级管理员可用
        """
        cookie_username = request.COOKIES.get('username').encode('latin-1').decode('utf-8')
        param: dict = json.loads(request.body)
        if cookie_username is None:
            # 无cookie信息，注册账号
            ret, code, message = param_register_user(param)
            return add_user(param, ret, code, message)
        else:
            # 有cookie信息，管理员添加账号
            try:
                # 获取管理员信息
                administrators = User.objects.get(username=cookie_username)
                ret, code, message = param_add_user(param, administrators)
                if administrators.username == 'root':
                    # 超级管理员添加用户，允许设置用户身份权限信息
                    return add_user(param, ret, code, message, set_role=True)
                else:
                    return add_user(param, ret, code, message)
            except User.DoesNotExist:
                logger.error(f'不存在{cookie_username}')
                return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))

    @staticmethod
    def view_sign_in(request: HttpRequest):
        """
        用户登录
        """
        if request.method == 'POST':
            param: dict = json.loads(request.body)
            username = param.get('username')
            password = param.get('password')
            if (username is None or username == ''
                    and password is None or password == ''):
                return UnSureJsonResponse(Result.fail(code=1001, message='缺少必要参数'))
            else:
                password = get_md5_encryption(password)
                try:
                    user = User.objects.get(username=username)
                    if user.password == password:
                        response = UnSureJsonResponse(Result.success(data=user, delete=['is_removed', 'password']))
                        response.set_cookie('username', username.encode('utf-8').decode('latin-1'))
                        return response
                    else:
                        return UnSureJsonResponse(Result.fail(code=2006, message='用户名或密码错误'))
                except User.DoesNotExist:
                    logger.error(f'不存在{username}')
                    return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))
                except User.MultipleObjectsReturned:
                    logger.error(f'存在多个用户{username}')
                    return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))
        else:
            return UnSureJsonResponse(Result.fail(code=1004, message='请求方法错误'))

    @staticmethod
    def put(request: HttpRequest):
        """
        修改账号信息
        """
        cookie_username = request.COOKIES.get('username').encode('latin-1').decode('utf-8')
        param: dict = json.loads(request.body)

        try:
            # 获取管理员信息
            administrators = User.objects.get(username=cookie_username)
            # 允许修改标记
            flag_change = False
            if administrators.role == 1:
                # 是管理员
                flag_change = True
            else:
                # 判断是否为当前用户
                username = param.get('username')
                if cookie_username == username:
                    flag_change = True
            if flag_change:
                user = User.objects.get(username=param.get('username'))
                if param.get('nickname') is not None or param.get('nickname') != '':
                    user.nickname = param.get('nickname')
                # 存在修改用户身份权限信息，且是超级管理员操作，修改的用户不能是超级管理员
                if ((param.get('role') == 1 or param.get('role') == 0)
                        and administrators.username == 'root'
                        and user.username != 'root'):
                    user.role = param.get('role')
                user.save()
                user.role_int2role_message()
                return UnSureJsonResponse(Result.success(data=user, delete=['is_removed', 'password']))
            else:
                return UnSureJsonResponse(Result.fail(code=1002, message='无权限'))
        except User.DoesNotExist:
            logger.error(f'不存在{cookie_username}')
            return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))

    @staticmethod
    def view_change_user_password(request: HttpRequest):
        """
        修改用户密码
        """
        if request.method == 'PUT':
            cookie_username = request.COOKIES.get('username').encode('latin-1').decode('utf-8')
            param: dict = json.loads(request.body)

            try:
                username = param.get('username')
                # 允许修改标记
                if cookie_username == username:
                    flag_change = True
                else:
                    flag_change = False
                if flag_change:
                    ret, code, message = change_password(param)
                    if ret:
                        # 修改密码成功
                        user = User.objects.get(username=param.get('username'))
                        return UnSureJsonResponse(Result.success(data=user, delete=['is_removed', 'password']))
                    else:
                        # 修改密码失败
                        return UnSureJsonResponse(Result.fail(code=code, message=message))
                else:
                    return UnSureJsonResponse(Result.fail(code=1002, message='无权限'))
            except User.DoesNotExist:
                logger.error(f'不存在{cookie_username}')
                return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))
        else:
            return UnSureJsonResponse(Result.fail(code=1004, message='请求方法错误'))

    @staticmethod
    def delete(request: HttpRequest):
        """
        删除用户
        """
        cookie_username = request.COOKIES.get('username').encode('latin-1').decode('utf-8')
        param: dict = json.loads(request.body)

        if param.get('username') == 'root':
            return UnSureJsonResponse(Result.fail(code=1003, message='无法删除超级管理员'))

        try:
            # 获取管理员信息
            administrators = User.objects.get(username=cookie_username)
            # 允许修改标记
            flag_delete = False
            if administrators.role == 1:
                # 是管理员
                flag_delete = True
            else:
                # 判断是否为当前用户
                username = param.get('username')
                if cookie_username == username:
                    flag_delete = True
            if flag_delete:
                user = User.objects.get(username=param.get('username'))
                user.delete()
                return UnSureJsonResponse(Result.success())
            else:
                return UnSureJsonResponse(Result.fail(code=1002, message='无权限'))
        except User.DoesNotExist:
            logger.error(f'不存在{cookie_username}')
            return UnSureJsonResponse(Result.fail(code=2002, message='用户身份异常'))
